package com.jiawa.train.business.controller;

import com.jiawa.train.business.req.ConfirmOrderDoReq;
import com.jiawa.train.business.service.BloomFilterService;
import com.jiawa.train.business.service.ConfirmOrderService;
import com.jiawa.train.common.exception.BusinessException;
import com.jiawa.train.common.resp.CommonResp;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

import static com.jiawa.train.common.exception.BusinessExceptionEnum.BUSINESS_SYSTEM_BUSY;
import static com.jiawa.train.common.exception.BusinessExceptionEnum.TRAIN_CODE_NOT_EXIST;

@RestController
@RequestMapping("/confirm-order")
public class ConfirmOrderController {

    @Resource
    private ConfirmOrderService confirmOrderService;
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private BloomFilterService bloomFilterService;
    private static final Logger LOG = LoggerFactory.getLogger(ConfirmOrderService.class);
    @PostMapping("/do")
    public void doConfirm(@Valid @RequestBody ConfirmOrderDoReq req) {

        if (!bloomFilterService.contains(req.getTrainCode())) {
            // 如果布隆过滤器认为不存在，直接拦截

            LOG.warn("布隆过滤器拦截，疑似非法车次代码: {}", req.getTrainCode());
            throw new BusinessException(TRAIN_CODE_NOT_EXIST);
        }
        //获取redisson分布式锁
        String lockKey = String.format("train_ticket_lock:%s:%s:%s:%s",
                req.getTrainCode(), req.getDate(), req.getStart(), req.getEnd());
        RLock lock = redissonClient.getLock(lockKey);

        try {
            boolean isLocked = lock.tryLock(10, 5, TimeUnit.SECONDS);
            if (!isLocked) {
                throw new BusinessException(BUSINESS_SYSTEM_BUSY);
            }

            // 查余票、扣减余票、生成订单等逻辑
            confirmOrderService.doConfirm(req);

        } catch (InterruptedException e) {
            throw new BusinessException(BUSINESS_SYSTEM_BUSY);
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

}
